package mysql

import (
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Account   string `gorm:"type:char(11);not null;comment:'手机号'"`
	Password  string `gorm:"type:char(32);not null;comment:'密码'"`
	UserImage string `gorm:"type:varchar(500);not null;comment:'用户头像'"`
	Info      string `gorm:"type:varchar(50);not null;comment:'简介'"`
	NickName  string `gorm:"type:varchar(50);not null;comment:'用户昵称'"`
}
type UserRealName struct {
	gorm.Model
	UserId   int    `gorm:"type:int;not null;comment:'用户ID'"`
	Realname string `gorm:"type:varchar(20);not null;comment:'真实姓名'"`
	IDCard   string `gorm:"type:char(18);not null;comment:'身份证号'"`
}

func (u *User) GetUserInfo() error {
	return DB.Where("account =?", u.Account).Find(&u).Error
}

func (u *User) GetUserInfoById() error {
	return DB.Where("id =?", u.ID).Find(&u).Error
}

func (u *User) CreateUser() error {
	return DB.Create(&u).Error
}

func (r UserRealName) RealName() error {
	return DB.Where("user_id =?", r.UserId).Limit(1).Find(&r).Error

}

func (r *UserRealName) CreateRealname() error {
	return DB.Debug().Create(&r).Error
}
func (u *User) List(keyword string, page, pageSize int) (userList []*User, err error) {
	err = DB.Where("id =?", u.ID).Where("nick_name like ?", "%"+keyword+"%").Find(&userList).Scopes(Paginate(page, pageSize)).Error
	return
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
